<template>
  <el-dialog
    v-bind="$attrs"
    :title="$t('developer.add_developer')"
    width="600px"
    @open="handleOpen"
    @close="handleClose"
  >
    <el-form
      ref="developerForm"
      label-position="top"
      :rules="operatorRules"
      :model="developerForm"
    >
      <el-form-item prop="email" key="email" :label="$t('login.email')">
        <el-input :maxlength="64" v-model="developerForm.email"></el-input>
      </el-form-item>
      <el-form-item
        :label="$t('login.developer_type')"
        required
        prop="developerType"
        key="developerType"
      >
        <el-select
          v-model="developerForm.developerType"
          @change="clearDeveloperValidate"
          class="w-full"
        >
          <el-option :key="1" :value="1" :label="$t('login.personal')"></el-option>
          <el-option :key="2" :value="2" :label="$t('login.company')"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="developerForm.developerType == 1"
        required
        :label="$t('login.first_name')"
        prop="firstName"
        key="firstName"
      >
        <el-input
          :maxlength="64"
          v-model="developerForm.firstName"
          @blur="() => (developerForm.firstName = developerForm.firstName.trim())"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="developerForm.developerType == 1"
        required
        :label="$t('login.last_name')"
        prop="lastName"
        key="lastName"
      >
        <el-input
          :maxlength="64"
          v-model="developerForm.lastName"
          @blur="() => (developerForm.lastName = developerForm.lastName.trim())"
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="developerForm.developerType == 2"
        required
        :label="$t('login.company_name1')"
        prop="firstName"
        key="firstName"
      >
        <el-input
          :maxlength="64"
          v-model="developerForm.firstName"
          @blur="() => (developerForm.firstName = developerForm.firstName.trim())"
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="developerForm.developerType == 1"
        :label="$t('login.certificate_type')"
      >
        <el-select v-model="developerForm.pidType" class="w-full">
          <el-option :key="1" :value="1" :label="$t('login.id_card')"></el-option>
          <el-option :key="2" :value="2" :label="$t('login.passport')"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('login.certificate_num')">
        <el-input v-model="developerForm.pid" :maxlength="32"></el-input>
      </el-form-item>
      <el-form-item
        v-if="developerForm.developerType == 2"
        required
        :label="$t('login.contacts')"
        prop="contactName"
        key="contactName"
      >
        <el-input
          :maxlength="64"
          v-model="developerForm.contactName"
          @blur="() => (developerForm.contactName = developerForm.contactName.trim())"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('login.phone_number')" prop="mobile" key="mobile">
        <el-input v-model.trim="developerForm.mobile" :maxlength="16"></el-input>
      </el-form-item>
      <el-form-item required prop="countryCode" class="country-code" key="countryCode">
        <template #label>
          <div class="inline-block">
            {{ $t("login.country_region") }}
          </div></template
        >
        <el-select
          v-model="developerForm.countryCode"
          :no-match-text="$t('common.no_data')"
          filterable
          class="w-full"
        >
          <el-option
            v-for="item in countries"
            :key="item.countryCode3"
            :label="item.countryNameEn"
            :value="item.countryCode3"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('login.address1')">
        <el-input
          v-model="developerForm.address"
          :maxlength="128"
          type="textarea"
          :rows="2"
        ></el-input>
      </el-form-item>
      <div class="flex-1">
        <hr class="mt-3 border-divider" />
        <el-form-item
          :label="$t('login.password')"
          required
          prop="password"
          type="password"
        >
          <el-input
            v-model="developerForm.password"
            :maxlength="64"
            type="password"
          ></el-input>
          <div class="password-strength" v-show="showPasswordStrength">
            <div class="text">
              {{ $t("login.password_strength") }}
              {{ mapPasswordStrength[passwordStrength] }}
            </div>
            <div class="indicator">
              <span :class="['weak', { active: passwordStrength >= 1 }]"></span>
              <span :class="['moderate', { active: passwordStrength >= 2 }]"></span>
              <span :class="['strong', { active: passwordStrength === 3 }]"></span>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('login.confirm_password')"
          required
          prop="confirmPassword1"
          type="password"
        >
          <el-input v-model="developerForm.confirmPassword1" type="password"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button text @click="handleClose">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="createDeveloper()">{{
          $t("common.confirm")
        }}</el-button>
      </span></template
    >
  </el-dialog>
</template>

<script>
import { getCountryList } from "@/api/user";

import { createDeveloper } from "@/api/developer";
const MAP_PASSWORD_STRENGTH = {
  1: "Weak",
  2: "Moderate",
  3: "Strong",
};
export default {
  name: "AddDeveloper",
  data() {
    const validPassword = function (rule, password, cb) {
      if (password) {
        this.showPasswordStrength = true;
        this.passwordStrength = 1;
        if (password.length < 8) {
          cb(new Error(this.$t("login.validate_password_tip")));
        } else {
          if (password.length > 18) {
            cb(new Error(this.$t("login.validate_password_tip")));
          }
          this.showPasswordStrength = true;
          var hasUpperCase = /[A-Z]/.test(password);
          var hasLowerCase = /[a-z]/.test(password);
          var hasNumbers = /\d/.test(password);
          var hasNonalphas = /\W/.test(password);

          var complexity = hasUpperCase + hasLowerCase + hasNumbers + hasNonalphas;
          if (complexity <= 2) {
            this.passwordStrength = 1;
            cb(new Error(this.$t("login.validate_password_strength")));
          } else if (complexity === 3) {
            this.passwordStrength = 2;
          } else if (complexity === 4) {
            this.passwordStrength = 3;
          }
        }
      } else {
        this.showPasswordStrength = false;
        cb(new Error(this.$t("login.validate_password_required")));
      }
      cb();
    };

    const validConfirmPassword = function (rule, password, cb) {
      if (!password) {
        cb(new Error(this.$t("login.validate_confirm_password_required")));
      }
      if (password !== this.operatorForm.password) {
        cb(new Error(this.$t("login.consistent_password_tip")));
      } else {
        cb();
      }
    };
    const validConfirmPassword1 = function (rule, password, cb) {
      if (!password) {
        cb(new Error(this.$t("login.validate_confirm_password_required")));
      }
      if (password !== this.developerForm.password) {
        cb(new Error(this.$t("login.consistent_password_tip")));
      } else {
        cb();
      }
    };

    const validFile = function (rule, file, cb) {
      if (this.fileList.length < 1) {
        cb(new Error(this.$t("login.file_required")));
      } else {
        cb();
      }
    };

    const validCountry = function (rule, country, cb) {
      if (!country) {
        cb(new Error(this.$t("login.country_required")));
      } else {
        cb();
      }
    };

    const validateFirstName = function (rule, value, cb) {
      if (!value) {
        if (this.developerForm.developerType === 1) {
          cb(new Error("First Name is required"));
        } else if (this.developerForm.developerType === 2) {
          cb(new Error(this.$t("login.invalid_companyname")));
        }
      } else {
        cb();
      }
    };
    return {
      countries: [],
      confirmLoading: false,
      mapPasswordStrength: MAP_PASSWORD_STRENGTH,
      showPasswordStrength: false,
      passwordStrength: 0,
      developerForm: {
        // 开发者类型，1-个人；2-公司
        developerType: 2,
        // developer_type = 1时表示名字; developer_type = 2时表示 公司名称
        firstName: "",
        lastName: "",
        contactName: "",
        mobile: "",
        email: "",
        username: "",
        password: "",
        confirmPassword1: "",
        // 证件类型 Integer
        pidType: 1,
        pid: "",
        countryCode: "",
        address: "",
      },
      operatorRules: {
        email: [
          {
            required: true,
            message: this.$t("login.email_required"),
          },
          {
            type: "email",
            message: this.$t("login.invalid_email_format"),
          },
          {
            max: 64,
            message: this.$t("login.invalid_email_length"),
          },
        ],
        firstName: [
          {
            validator: validateFirstName.bind(this),
          },
        ],

        lastName: [
          {
            required: true,
            message: this.$t("login.invalid_lastname"),
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("login.invalid_companyname"),
          },
        ],
        address: [{ required: true }],
        file: [
          {
            validator: validFile.bind(this),
          },
        ],
        countryCode: [
          {
            validator: validCountry.bind(this),
          },
        ],
        password: [
          {
            validator: validPassword.bind(this),
          },
        ],
        contactName: [
          {
            required: true,
            message: this.$t("login.invalid_contactname"),
          },
        ],
        confirmPassword: [
          {
            validator: validConfirmPassword.bind(this),
          },
        ],
        confirmPassword1: [
          {
            validator: validConfirmPassword1.bind(this),
          },
        ],
        mobile: [
          {
            max: 16,
            message: this.$t("login.validate_phone_tip"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getCountryList();
  },
  methods: {
    getCountryList() {
      getCountryList()
        .then((res) => {
          this.countries = res;
        })
        .catch((err) => {
          this.$confirmError(err);
        });
    },
    clearDeveloperValidate() {
      this.$refs["developerForm"].clearValidate();
    },
    createDeveloper() {
      this.$refs.developerForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          const formData = {};
          formData.username = this.developerForm.email;
          formData.developerType = this.developerForm.developerType;
          formData.firstName = this.developerForm.firstName;
          formData.lastName = this.developerForm.lastName;
          if (this.developerForm.developerType == 2) {
            formData.contactName = this.developerForm.contactName;
          } else {
            formData.contactName =
              this.developerForm.firstName + " " + this.developerForm.lastName;
          }

          formData.mobile = this.developerForm.mobile;
          formData.email = this.developerForm.email;
          formData.countryCode = this.developerForm.countryCode;
          formData.address = this.developerForm.address;
          if (this.developerForm.developerType == 2) {
            formData.pidType = 3;
          } else {
            formData.pidType = this.developerForm.pidType;
          }
          formData.pid = this.developerForm.pid;
          formData.password = this.developerForm.password;

          createDeveloper(formData)
            .then((res) => {
              this.confirmLoading = false;
              this.handleClose();
            })
            .catch((err) => {
              this.confirmLoading = false;
              this.$confirmError(err);
            });
        }
      });
    },

    handleOpen() {
      this.operatorRules.email = [
        {
          required: true,
          message: this.$t("login.email_required"),
        },
        {
          type: "email",
          message: this.$t("login.invalid_email_format"),
        },
        {
          max: 64,
          message: this.$t("login.invalid_email_length"),
        },
      ];

      this.operatorRules.lastName = [
        {
          required: true,
          message: this.$t("login.invalid_lastname"),
        },
      ];
      this.operatorRules.name = [
        {
          required: true,
          message: this.$t("login.invalid_companyname"),
        },
      ];
      this.operatorRules.contactName = [
        {
          required: true,
          message: this.$t("login.invalid_contactname"),
        },
      ];

      this.operatorRules.mobile = [
        {
          max: 16,
          message: this.$t("login.validate_phone_tip"),
          trigger: "blur",
        },
      ];
    },
    handleClose() {
      this.showPasswordStrength = false;
      this.developerForm = {
        // 开发者类型，1-个人；2-公司
        developerType: 2,
        // developer_type = 1时表示名字; developer_type = 2时表示 公司名称
        firstName: "",
        lastName: "",
        contactName: "",
        mobile: "",
        email: "",
        username: "",
        password: "",
        confirmPassword1: "",
        // 证件类型 Integer
        pidType: 1,
        pid: "",
        countryCode: "",
        address: "",
      };
      this.$refs.developerForm.resetFields();
      this.$emit("refreshDataList");
      this.confirmLoading = false;
      this.$emit("update:model-value", false);
    },
  },
};
</script>

<style lang="scss" scoped>
.password-strength {
  .text {
    line-height: 12px;
    margin-top: 10px;
    font-size: 12px;
  }

  color: #606266;
}

.indicator {
  width: 180px;
  height: 5px;
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  span {
    position: relative;
    height: 100%;
    width: 100%;
    background: lightgrey;

    &::before {
      width: 0;
      position: absolute;
      height: 100%;
      content: "";
      top: 0;
      left: 0;
      transition: width 0.5s;
    }

    /* border-radius: 5px; */
    &.weak::before {
      background-color: #ff4757;
    }

    &.moderate::before {
      background-color: orange;
    }

    &.strong::before {
      background-color: #9acb6b;
    }

    &.active::before {
      width: 100%;
    }

    &:nth-child(2) {
      margin: 0 3px;
    }
  }
}
</style>
